<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\api\permissions;

use App\Common\Repositories\System\CustomerPermissionsRepository;
use App\Exception\AppException;
use xsl\basic\BaseController;
use xsl\enums\Status;

class Permissions extends BaseController
{
    protected $repository;

    public function __construct(CustomerPermissionsRepository $repository)
    {
        $this->repository = $repository;
    }

    public function index()
    {
        if ($this->request->input('from') == 'role') {
            $where['my_type'] = 0;
            return $this->success($this->repository->getList($where));
        }
        $where['type'] = [1, 2];
        $with = ['actions'];
        return $this->success($this->repository->getList($where, $with));
    }

    public function departments()
    {
        return $this->success();
    }

    public function enable($id)
    {
        try {
            return $this->success($this->repository->toggleBy($id, 'hidden'));
        } catch (AppException $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }

    public function delete($id)
    {
        return $this->success($this->repository->delete($id));
    }

    public function read($id)
    {
        return $this->success($this->repository->get($id));
    }

    public function create(){
        $params = $this->request->all();
        $params['creator_id'] = $this->request->adminId();

        return $this->success($this->repository->storeBy($params));
    }

    public function update($id){
        $params = $this->request->all();
        if(isset($params['created_at']))
            unset($params['created_at']);
        if(isset($params['updated_at']))
            unset($params['updated_at']);

        return $this->success($this->repository->update($id, $params));
    }
}
